/**
 * Creater with IntelliJ IDEA.
 * Description:
 * User: 86152
 * Dae: 2022-07-25
 * Time: 11:56
 */
public class Ticket implements Runnable{

    private int ticket = 5;
 
    Object object = new Object();  //将object作为锁对象

    public void run(){
        while (true){
            synchronized (object){    //将下面临界区代码锁住，保证A和B只有一个执行
                if (ticket > 0){
                    System.out.println(Thread.currentThread().getName() + "正在出售" + ticket + "号票");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ticket--;
                }else {
                    break;    //票卖完了就停止线程
                }
            }
        }
    }

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        Thread a = new Thread(ticket,"A");
        Thread b = new Thread(ticket,"B");

        a.start();
        b.start();
    }
}
